import {
    BASE_URL
} from '../../../http/config';
var WxParse = require('../../../wxParse/wxParse.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        article: [],
        pageNo: 1,
        totalPageCount: 0,
        isLoading: false,
        articleDetail: {},
        detail: {},
        img: BASE_URL,
         consultId: null
    },

   getArticle() {
       if (this.data.isLoading) return;

       this.setData({
           isLoading: true
       });

       wx.showLoading({
           title: '数据正在加载...'
       });

       const requestData = {
           pageNo: this.data.pageNo,
           pageSize: 10
       };

       // 如果有 consultId，则加入请求参数中
       if (this.data.consultId) {
           requestData.consultId = this.data.consultId;
       }

       wx.request({
           url: `${BASE_URL}/course/all`,
           data: requestData,
           method: 'GET',
           success: (res) => {
               console.log("文章列表数据：", res.data);

               if (res.data.code === 200) {
                   const newArticles = res.data.data.list || [];

                   const formattedArticles = newArticles.map(item => ({
                       ...item,
                       id: item.id,
                       url: item.url || '',
                       articleName: item.articleName || '无标题',
                       articleIntroduction: item.articleIntroduction || '暂无简介'
                   }));

                   this.setData({
                       article: this.data.pageNo === 1 ? formattedArticles : this.data.article.concat(formattedArticles),
                       totalPageCount: res.data.data.totalPageCount || 0
                   });
               } else {
                   wx.showToast({
                       title: res.data.message || '加载失败',
                       icon: 'none'
                   });
               }
           },
           fail: (err) => {
               console.error("获取文章列表失败：", err);
               wx.showToast({
                   title: '网络错误，加载失败',
                   icon: 'none'
               });
           },
           complete: () => {
               wx.hideLoading();
               wx.stopPullDownRefresh();
               this.setData({
                   isLoading: false
               });
           }
       });
   },

    

    getArticleDetail(articleId) {
        wx.request({
            url: `${BASE_URL}/article/findById/${articleId}`,
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    const result = res.data.data;
                    this.setData({
                        articleDetail: result
                    });
                    // 富文本解析
                    WxParse.wxParse('detail', 'html', result.content || '', this, 5);
                }
            }
        });
    },
    jumpCourseDetail(e) {
         const courseId = e.currentTarget.dataset.id;

      
        wx.navigateTo({
            url: `/course/pages/courseDetail/courseDetail?id=${courseId}`
        });
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
         if (options.consultId) {
             this.setData({
                 consultId: options.consultId
             });
         }
         this.getArticle();
       
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        //    this.reportReadDataToBackend();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.setData({
            article: [],
            pageNo: 1,
            totalPageCount: 0
        })
        this.getArticle()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.pageNo >= this.data.totalPageCount) {
            wx.showToast({
                title: '没有更多数据了',
                icon: 'none'
            })
            return
        }
        this.setData({
            pageNo: this.data.pageNo + 1
        })
        this.getArticle()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '文章列表',
            path: '/index/pages/articleList/articleList'
        };
    },
    reportReadDataToBackend() {
        const readCache = wx.getStorageSync('readCache') || {};

        const readList = Object.keys(readCache).map(id => ({
            id: parseInt(id),
            count: readCache[id].count
        }));

        if (readList.length === 0) return;

        wx.request({
            url: `${BASE_URL}/article/read/batch`,
            method: 'POST',
            data: readList,
            header: {
                'Content-Type': 'application/json'
            },
            success: (res) => {
                console.log("阅读量上报结果：", res.data);
                if (res.data.code === 200) {
                    wx.removeStorageSync('readCache');
                }
            },
            fail: (err) => {
                console.error("上报失败：", err);
            }
        });
    }

})